command_context.py 975 B

123456789101112131415161718192021222324252627282930313233343536
  1. from contextlib import contextmanager
  2. from pip._vendor.contextlib2 import ExitStack
  3. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  4. if MYPY_CHECK_RUNNING:
  5. from typing import Iterator, ContextManager, TypeVar
  6. _T = TypeVar('_T', covariant=True)
  7. class CommandContextMixIn(object):
  8. def __init__(self):
  9. # type: () -> None
  10. super(CommandContextMixIn, self).__init__()
  11. self._in_main_context = False
  12. self._main_context = ExitStack()
  13. @contextmanager
  14. def main_context(self):
  15. # type: () -> Iterator[None]
  16. assert not self._in_main_context
  17. self._in_main_context = True
  18. try:
  19. with self._main_context:
  20. yield
  21. finally:
  22. self._in_main_context = False
  23. def enter_context(self, context_provider):
  24. # type: (ContextManager[_T]) -> _T
  25. assert self._in_main_context
  26. return self._main_context.enter_context(context_provider)